﻿Imports System.Threading
Imports System.ComponentModel


Class Module1
    Shared rc As New replayController


    Public Shared Sub Main()
        Try
            Dim maxQueries As Integer

            Call CreateErrorLog()

            Console.WriteLine(String.Format("mdxReplay Tool v{0}", AssemblyVersion))
            Console.WriteLine("Free utility to replay MDX multi-threaded for cache warming or stress testing")
            Console.WriteLine("")
            Console.WriteLine(String.Format("Developed by Bob Duffy Prodata, {0}", Format(BuildDate, "dd/MM/yy")))
            Console.WriteLine()
            ParseCommandLine()

            maxQueries = replayController.CountQueries
            If maxQueries < My.Settings.MaxQueryCount Or My.Settings.MaxQueryCount < 1 Then My.Settings.MaxQueryCount = maxQueries

            Console.WriteLine("Current Settings:")
            Console.WriteLine(String.Format("SQL Connection String: {0}", My.Settings.sqlConnectionString))
            Console.WriteLine(String.Format("SQL MDX Queue Table: {0}", My.Settings.sqlTable))
            Console.WriteLine(String.Format("MDX Server: {0}/{1}/{2}", My.Settings.mdServerName, My.Settings.mdDatabaseName, My.Settings.mdCubeName))
            Console.WriteLine("Number of Threads: {0}", My.Settings.Threads)
            Console.WriteLine("ClearCache: {0}", My.Settings.ClearCache)
            If My.Settings.RunID > 0 Then Console.WriteLine("Continuing Run: {0}", My.Settings.RunID)

            Console.WriteLine("")
            Console.WriteLine("Testing connection to SQL Table with MDX queries...")
            SqlHelper.TestConnection()
            Console.WriteLine(String.Format("testing Connection to MDX Server {0}", My.Settings.mdServerName))
            Dim mdx As New MdxHelper
            mdx.Connect()
            mdx.TestConnection()
            Console.WriteLine("Loading Parameters Table...")
            mdx.LoadDefaults()

            If My.Settings.ClearCache = 1 Then
                mdx.ClearCache()
            End If
            mdx.DisConnect()

            Console.WriteLine("")
            If My.Settings.LogResults = 1 Then
                If My.Settings.RunLabel = "" Then My.Settings.RunLabel = Now.ToString
                replayController.StartLog()
                Console.WriteLine(String.Format("Logging to Database using RunID={0}", replayController.RunID))
            End If
            Console.WriteLine("Creating Worker Threads ...")
            rc.CreateWorkers(My.Settings.Threads)

            Console.WriteLine("Starting Threads ...")
            rc.StartController()

            Threading.Thread.Sleep(50)

            Console.WriteLine("")
            Console.WriteLine("** press (Control-C) to Cancel **")
            Console.WriteLine("")
            Console.WriteLine("")
            Console.WriteLine("Start Time : {0}", rc.startTime)

            While Worker.NumberOfThreads >= 1
                Threading.Thread.Sleep(500)

                If My.Settings.ShowProgress Then ShowProgress()
            End While
            If My.Settings.ShowProgress Then ShowProgress()

            rc.StopController()
            Console.WriteLine()
            Console.WriteLine("End Time   : {0}", rc.EndTime)
            Console.WriteLine(String.Format("Total Time : {0} Secs", rc.TickCount / 1000))
            Console.WriteLine("Avg Time   : {0} Secs per Query", Format(rc.TickCount / replayController.QueryCount * My.Settings.Threads / 1000, "0.00"))
        Catch ex As Exception
            Console.WriteLine("Error: " & ex.ToString)
        Finally
            If Debugger.IsAttached Then
                Console.ReadKey()
            End If

        End Try
    End Sub


    Public Sub MyWorker(ByVal sender As Object, ByVal e As DoWorkEventArgs)

    End Sub

    Public Shared Sub ParseCommandLine()
        Dim s() As String = System.Environment.GetCommandLineArgs
        For i = 0 To UBound(s)
            Select Case LCase(s(i))
                Case "-t"
                    My.Settings.Threads = LCase(s(i + 1))
                Case "-"
                Case "-s", "-ServerName"
                    My.Settings.mdServerName = s(i + 1)
                Case "-d", "-Database"
                    My.Settings.mdDatabaseName = s(i + 1)
                Case "-c", "-CubeName"
                    My.Settings.mdCubeName = s(i + 1)
                Case "-p", "-ShowProgress"
                    My.Settings.ShowProgress = True
                Case "-x", "-ClearCache"
                    My.Settings.ClearCache = s(i + 1)
                Case "-h", "-help", "-?"
                    Call ShowHelp()
                    End
                Case "-rl", "-l", "-Log", "-LogResults"
                    My.Settings.LogResults = 1
                Case "-RunLabel", "-Label"
                    My.Settings.RunLabel = s(i + 1)
            End Select
        Next
    End Sub


    Shared Sub ShowHelp()
        Console.WriteLine("Usage: mdxReplay.exe -t [Threads] -s [SSAS Server] -d [SSAS Database] -c [Cube] ")
        Console.WriteLine()
        Console.WriteLine("Miscelaneous Flags:")
        Console.WriteLine("-p [0,1] Show Progress")
        Console.WriteLine("-l [0,1] Log to Database")
        Console.WriteLine("-rl [Run Label for Logging]")



    End Sub
    Public Shared ReadOnly Property AssemblyVersion As String
        Get
            Return System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()
        End Get
    End Property


    Public Shared Function BuildDate() As Date
        Dim location As String = System.Reflection.Assembly.GetExecutingAssembly().Location
        Dim fi As New System.IO.FileInfo(location)
        Return fi.CreationTime
    End Function


    Public Shared Sub ShowProgress()
        Dim Success As Boolean = True

        Dim y = Console.CursorTop
        Console.SetCursorPosition(0, y)
        Console.Write(String.Format("Progress   : {0} Threads. Query Progress {1}/{2}. Errors {3} ", replayController.NumberOfThreads, replayController.CompletedQueryCount, My.Settings.MaxQueryCount, replayController.ErrorCount))
        Threading.Thread.Sleep(50)
    End Sub

    Private Shared Sub CreateErrorLog()
        Dim sFilePath As String = System.AppDomain.CurrentDomain.BaseDirectory

        My.Application.Log.DefaultFileLogWriter.CustomLocation = sFilePath
    End Sub

End Class